package com.hong.chapter4;

import java.io.*;

/**
 * @Auther: Administrator
 * @Date: 2018/7/17 23:51
 * @Description: 实现加解密
 */
public class DecryptClassLoader extends ClassLoader {
    /*文件路径*/
    private final static String DEFAULT_DIR ="C:\\Users\\Administrator\\IdeaProjects\\classLoader\\src\\main\\java\\com\\hong\\chapter4\\test";
    /**/
    private String dir = DEFAULT_DIR;

    public DecryptClassLoader(){
        super();
    }

    public DecryptClassLoader(ClassLoader parent){
        super(parent);
    }

    @Override
    protected Class<?> findClass(String name)
            throws ClassNotFoundException {
        String classPath = name.replace(".", "/");
        File classFile = new File(dir,classPath+".class");
        if(!classFile.exists()){
            throw new ClassNotFoundException("The class "+name+"not found under directory ["+dir+"]");
        }

        byte[] classBytes = loadClassBytes(classFile);

        if(null==classBytes || classBytes.length==0){
            throw new ClassNotFoundException("load the  class "+name+" failed");
        }

        return this.defineClass(name,classBytes,0,classBytes.length);
    }

    private byte[] loadClassBytes(File classFile) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             FileInputStream fis = new FileInputStream(classFile)) {
            int data;
            while ((data=fis.read())!=-1){
                baos.write(data^ EncryptUtils.ENCRYPT_FACTOR);
            }
            baos.flush();
            return  baos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    public void setDir(String dir) {
        this.dir = dir;
    }
}
